import nme.Assets;
import nme.display.Sprite;
import nme.display.Bitmap;
import nme.display.BitmapData;

import nme.geom.Rectangle;
import nme.geom.Matrix;
import nme.geom.Point;

class ModuleData
{
	public var name		(default, null):String;
	public var sprite	(default, null):SpriteData;
	public var bound	(default, null):Rectangle;
	public var rBound	(default, null):Rectangle;
	public var uvtData	(default, null):Array<Float>;
	
	public var index:Int;
	
	private function new (id:String, spr:SpriteData, srcRect:Rectangle)
	{
		name = id;
		sprite = spr;
		bound = srcRect;
		
		var temp:BitmapData = new BitmapData (cast bound.width, cast bound.height, true, 0x00000000);
		temp.copyPixels (sprite._src, bound, new Point (0, 0));
		rBound = temp.getColorBoundsRect(0xFFFFFF, 0xFFFFFF, false);
		temp.dispose ();
		
		var uvL:Float = (bound.x + rBound.left) / sprite._src.width;
		var uvR:Float = (bound.x + rBound.right) / sprite._src.width;
		var uvT:Float = (bound.y + rBound.top) / sprite._src.height;
		var uvB:Float = (bound.y + rBound.bottom) / sprite._src.height;
		uvtData = [uvL, uvT, uvR, uvT, uvR, uvB, uvL, uvB];
	}
	
	public static function create (moduleXml:Xml, sprite:SpriteData):ModuleData
	{
		var id:String = moduleXml.get("id");
		var r:Rectangle = new Rectangle (
			Std.parseInt (moduleXml.get("x")),
			Std.parseInt (moduleXml.get("y")),
			Std.parseInt (moduleXml.get("width")),
			Std.parseInt (moduleXml.get("height"))
		);
		// var a:BitmapData = new BitmapData (Std.int(r.width), Std.int(r.height), true, 0x000000);
		// a.copyPixels (src, r, new Point (0, 0));
		
		// return new ModuleData (id, a, r);
		return new ModuleData (id, sprite, r);
	}
	
	public function vertices (m:Matrix):Array<Float>
	{
		return [
			rBound.left * m.a + rBound.top * m.c + m.tx,		rBound.left * m.b + rBound.top * m.d + m.ty,
			rBound.right * m.a + rBound.top * m.c + m.tx,		rBound.right * m.b + rBound.top * m.d + m.ty,
			rBound.right * m.a + rBound.bottom * m.c + m.tx,	rBound.right * m.b + rBound.bottom * m.d + m.ty,
			rBound.left * m.a + rBound.bottom * m.c + m.tx,		rBound.left * m.b + rBound.bottom * m.d + m.ty,
		];
	}
}